package seedpod.webapp.view.seedpodwidgets;

/**
 * CollectionWidget handles rendering of a collection of widgets
 */
import seedpod.exceptions.InvalidWidgetException;
import seedpod.model.AVPair;
import seedpod.model.SeedpodDO;
import seedpod.model.ValueSetRelationship;

public class CollectionWidget extends LimsWidget {

	protected ValueSetRelationship _valueSet = null;

	protected LimsWidget _widgetTool = null;

	/**
	 * Use this constructor to create a collection widget with the specified LimsWidget
	 * 
	 * @param widgetType
	 * @param avPair
	 */
	public CollectionWidget(AVPair avPair, LimsWidget widget) {
		super( avPair );
		setData( avPair.getValue() );
		setId( avPair.genRefId() );
		_widgetTool = widget;
	}

	@Override
	public String doEdit() {
		if ( _widgetTool.supportsMultiValueInput() ) {
			_widgetTool.setData( _valueSet.getTargetObjects() );
			return _widgetTool.doEdit();
		} else {
			String viewHTML = "";
			_widgetTool.setId( getId() );
			for ( Object o : _valueSet.getTargetObjects() ) {
				_widgetTool.setData( o );
				viewHTML += _widgetTool.doEdit();
			}
			return viewHTML;
		}
	}

	@Override
	public void doPost( SeedpodDO obj, Object input ) {}

	@Override
	public String doView() {
		if ( _widgetTool.supportsMultiValueInput() ) {
			_widgetTool.setData( _valueSet.getTargetObjects() );
			return _widgetTool.doView();
		} else {
			String viewHTML = "";
			_widgetTool.setId( getId() );
			for ( Object o : _valueSet.getTargetObjects() ) {
				_widgetTool.setData( o );
				viewHTML += _widgetTool.doView();
			}
			return viewHTML;
		}
	}

	@Override
	public ValueSetRelationship getData() {
		return _valueSet;
	}

	@Override
	public String render() {
		return doView();
	}

	@Override
	public void setData( Object data ) {
		_valueSet = data instanceof ValueSetRelationship ? (ValueSetRelationship)data : null;
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		if ( !getAttribute().isMultiple() )
			throw new InvalidWidgetException( "(E) The collection widget requires the data to have more than one value. " );

		if ( getData() != null && !(getData() instanceof ValueSetRelationship) )
			throw new InvalidWidgetException( "(E)The collection widget expects a value set as its input. " );
	}
}
